<!--需求列表 DemandCustomer-->
<template>
  <div class='page_format'>
    <!-- 顶部统计部分 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :span="4" v-for="(item, index) in statisticsData" :key="index">
        <div class="stat-box">
          <p>{{ item.label }}</p>
          <h3>{{ item.value }}</h3>
        </div>
      </el-col>
    </el-row>
    <div class="my_Select">
      <el-form :inline="true" class="search-form">
        <el-form-item>
          <el-button v-if="userName" class="bt-color-tjd" type="primary" style="margin-right: 10px;"
                     @click="retPath">返回
          </el-button>
          <el-button class="bt-color-tjd" type="primary"  style="margin-right: 10px;"
                     v-if="is_show_button('button_demand_crs_add') && !userName"
                     @click="saveDataForm">添加
          </el-button>
          <el-select style="width: 110px; margin-right: 10px;" v-model="status" placeholder="全部" size="small" clearable
                     @change="handleQuery">
            <el-option
              v-for="(item, index) in statusData"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-input style="width:120px;margin-right:6px" size="small" placeholder="需求名称" v-model="queryValue"
                    clearable></el-input>
          <el-button size="small" @click="handleQuery" icon="el-icon-search" type="primary">查询</el-button>
        </el-form-item>
<!--        <el-form-item>-->
<!--          <el-select v-model="kind" placeholder="品类" clearable style="width:120px;margin-right:6px" size="small"-->
<!--                     @change="handleQuery">-->
<!--            <el-option-->
<!--              v-for="item in deviceKindData"-->
<!--              :key="item.id"-->
<!--              :label="`${item.label}`"-->
<!--              :value="item.value"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item>

        </el-form-item>
      </el-form>
    </div>
    <el-table :data="list" border style="width: 100%">
      <el-table-column type="index" :index="sort" label="序号" width="50"></el-table-column>
      <el-table-column prop="demandId" label="ID"></el-table-column>
      <el-table-column prop="demandName" label="需求名称"/>
      <el-table-column prop="priority" label="优先级" width="80"/>
      <el-table-column label="数量/大小" align="center">
        <template v-slot="scope">
          <div><span>{{ scope.row.dailIdCount }}</span></div>
          <div><span>（{{ scope.row.dialSizeTotal }}kb，{{ scope.row.resSizeTotal }}kb）</span></div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template v-slot="scope">
          <span>{{ getStatusText(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否带缩略图">
        <template v-slot="scope">
          <span>{{ scope.row.thumbnailStatus === '0' ? '否' : '是' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备信息" align="left">
        <template v-slot="scope">
          <div><span>分辨率：{{ scope.row.devScrDpi }}</span></div>
          <div><span>主控平台：{{ getMasterControlPlatformText(scope.row.devIcMseries) }}</span></div>
          <div><span>主控型号：{{ scope.row.devIcMcode }}</span></div>
          <div><span>屏幕形状：{{ getShapeText(scope.row.devScrShape)}}</span></div>
        </template>
      </el-table-column>
      <el-table-column label="品类" width="80">
        <template v-slot="scope">
          <span>{{ getDeviceKindText(scope.row.kind) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column prop="finishTime" label="预计完成时间"/>
      <el-table-column v-if="!userName" fixed="right" label="操作" width="80">
        <template v-slot="scope">
          <div>
            <el-button @click="handleDetail(scope.row)" type="text" size="small">
              查看
            </el-button>
          </div>
          <div v-if="is_show_button('button_demand_crs_edit') && scope.row.status === '0'">
            <el-button @click="handleAnnexClick(scope.row)" type="text" size="small">
              {{ !scope.row.annexUrl ? '添加附件' : '替换附件' }}
            </el-button>
          </div>
          <div v-if="is_show_button('button_demand_crs_edit') && scope.row.status === '0' && scope.row.kind !== '2'">
            <el-button @click="handleClick(scope.row)" type="text" size="small">
              变更
            </el-button>
          </div>
          <div v-if="is_show_button('button_demand_crs_cancel') && scope.row.status === '0'">
            <el-button @click="changeStatus4(scope.row)" type="text" size="small">
              取消
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="!form.annexUrl ?'添加附件':'替换附件'" :visible.sync="annexDialogShow" center width="500px"
               @close="closeAnnexDialog">
      <el-form :model="form">
        <el-form-item label="需求附件：" :label-width="formLabelWidth">
          <!-- 自定义上传组件 -->
          <upLoads up_type="bin" :name="form.annexName" @chang_up="customUpload"></upLoads>
          <!-- 上传文件类型提示文本 -->
          <div style="margin-top: 8px; color: #999; font-size: 12px;">仅支持 Excel、Word 格式；</div>
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAnnexDialog" :disabled="submitLoading">取 消</el-button>
        <el-button class="bt-color-tjd" v-if="is_show_button('demand_in_save')" type="primary"
                   @click="saveAnnexDataApi" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加需求" :visible.sync="dialogFormVisible" center width="500px" @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="dialogForm">
        <el-form-item label="项目经理：" :label-width="formLabelWidth" prop="projectManager">
          <el-select v-model="form.projectManager" placeholder="请选择项目经理" style="width: 100%;" filterable clearable>
            <el-option
              v-for="item in userData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="需求名称：" :label-width="formLabelWidth" prop="demandName">
          <el-input v-model="form.demandName" placeholder="请输入需求名称" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 需求类型 -->
        <el-form-item label="需求类型：" :label-width="formLabelWidth" prop="kind">
          <el-select v-model="form.kind" placeholder="请选择需求类型" style="width: 100%;">
            <el-option
              v-for="item in filteredKindData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 优先级 -->
        <el-form-item label="优先级：" :label-width="formLabelWidth" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%;">
            <el-option
              v-for="item in priorityData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="项目类型：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;"
                      prop="type">
          <el-select v-model="form.type" placeholder="请选择项目类型" style="width: 100%;">
            <el-option
              v-for="item in typeData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="主控平台系列：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;"
                      prop="devIcMseries">
          <el-select v-model="form.devIcMseries" placeholder="请选择主控平台系列" style="width: 100%;">
            <el-option
              v-for="item in devIcMseriesData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主控型号：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;"
                      prop="devIcMcode">
          <el-select v-model="form.devIcMcode" placeholder="请选择主控型号" style="width: 100%;">
            <el-option
              v-for="item in devIcMcodeData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="屏幕形状：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;"
                      prop="devScrShape">
          <el-select v-model="form.devScrShape" placeholder="请选择屏幕形状" style="width: 100%;">
            <el-option
              v-for="item in devScrShapeData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="分辨率：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;" prop="devScrDpi">
          <el-select v-model="form.devScrDpi" placeholder="请选择分辨率" style="width: 100%;">
            <el-option
              v-for="item in devScrDpiData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否带缩略图：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;"
                      prop="thumbnailStatus">
          <el-select v-model="form.thumbnailStatus" placeholder="设备内是否带缩略图" style="width: 100%;">
            <el-option
              v-for="item in thumbnailStatusData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- Flash规格 -->
        <el-form-item label="Flash规格：" :label-width="formLabelWidth" prop="devIcFlash">
          <el-select v-model="form.devIcFlash" placeholder="请选择Flash规格" style="width: 100%;">
            <el-option
              v-for="item in devIcFlashData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="需求附件：" :label-width="formLabelWidth">
          <!-- 自定义上传组件 -->
          <upLoads up_type="bin" :name="form.annexName" @chang_up="customUpload"></upLoads>
          <!-- 上传文件类型提示文本 -->
          <div style="margin-top: 8px; color: #999; font-size: 12px;">仅支持 Excel、Word 格式；</div>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注：" :label-width="formLabelWidth">
          <el-input v-model="form.remark" placeholder="请输入介绍信息" autocomplete="off" type="textarea"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" :disabled="submitLoading">取 消</el-button>
<!--        <el-button class="bt-color-tjd" v-if="is_show_button('demand_in_save')" type="primary"-->
<!--                   @click="nextDialog" :loading="submitLoading">下一步</el-button>-->
        <el-button class="bt-color-tjd" v-if="is_show_button('demand_in_save') && form.kind !== '2'"  type="primary"
          @click="nextDialog" :loading="submitLoading" >
          下一步
        </el-button>
        <el-button v-if="is_show_button('demand_in_save') && form.devScrShape === '9'" class="bt-color-tjd"
                   type="primary"
                   @click="prepareFormDataAndSubmit" :loading="submitLoading" >
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="form.id ?'添加需求':'编辑需求'" :visible.sync="showImportData" width="1200px"
               @close="cancelImportDataDialog" >
      <div style="margin-top: -20px;margin-bottom: 10px;">
        <el-select v-model="importData.dialType" placeholder="表盘类型" style="width: 110px; margin-right:8px" size="small" clearable
                   @change="handleImportDataQuery">
          <el-option
            v-for="(item, index) in dialTypeData"
            :key="index"
            :label="`${item.label}`"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select v-model="importData.dialSize" placeholder="含缩略图表盘大小" style="width: 155px; margin-right:8px"
                   size="small" clearable
                   @change="handleImportDataQuery">
          <el-option
            v-for="(item, index) in dialSizeData"
            :key="index"
            :label="`${item.label}`"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select v-model="importData.resSize" placeholder="不含缩略图表盘大小" style="width: 165px; margin-right:8px"
                   size="small" clearable
                   @change="handleImportDataQuery">
          <el-option
            v-for="(item, index) in dialSizeData"
            :key="index"
            :label="`${item.label}`"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-input style="width:140px;margin-right:8px" size="small" placeholder="表盘名称" v-model="importData.queryValue"
                  clearable></el-input>
        <el-button size="small" @click="handleImportDataQuery" icon="el-icon-search" type="primary">查询</el-button>
      </div>
      <el-table :data="importData.list" border style="width: 100%;" max-height="500" v-loading="importData.loading" :row-key="rowKey"
                :default-selected="importData.multipleSelection" @selection-change="selectImportIds" ref="importTable">
        <el-table-column type="selection" width="40" align="center"></el-table-column>
        <el-table-column type="index" fixed :index="sort" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="dialId" label="表盘ID" align="center"></el-table-column>
        <el-table-column prop="dialNameZh" label="表盘名称" align="center"></el-table-column>
        <el-table-column label="预览图" width="144" align="center">
          <template v-slot="scope">
            <img style="width: 120px;" :src="scope.row.newPreviewUrl" alt="预览图">
          </template>
        </el-table-column>
        <el-table-column label="表盘大小（含缩略图）" align="center" >
          <template v-slot="scope">
            {{scope.row.dialSize}}kb
          </template>
        </el-table-column>
        <el-table-column label="表盘大小（不含缩略图）" align="center" >
          <template v-slot="scope">
            {{ scope.row.resSize }}kb
          </template>
        </el-table-column>
        <el-table-column label="表盘类型" align="center" >
          <template v-slot="scope">
            <span>{{ getDialTypeText(scope.row.dialTypeId) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px; text-align: left;">
        已选 {{ importData.selectedCount }} 个表盘 所占空间：
        <br />
        bin 含缩略图：{{ importData.totalDialSize.toFixed(3) }} KB
        <br />
        bin 不含缩略图：{{ importData.totalResSize.toFixed(3) }} KB
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelImportDataDialog">取 消</el-button>
        <el-button class="bt-color-tjd" v-if="is_show_button('demand_in_save')" :loading="importData.submitLoading"
                   type="primary" @click="saveDataApi">提 交</el-button>
      </div>

<!--      <el-pagination-->
<!--        style="position:relative;margin: 20px 0 10px;padding: 0;box-shadow: none;"-->
<!--        @size-change="importSizeChange"-->
<!--        @current-change="importCurrentChange"-->
<!--        :current-page="importData.pageNum"-->
<!--        :page-sizes="[10, 20, 30, 50]"-->
<!--        :page-size="importData.pageSize"-->
<!--        layout="total, sizes, prev, pager, next, jumper"-->
<!--        :total="importData.total">-->
<!--      </el-pagination>-->
    </el-dialog>

    <el-dialog title="查看需求详情" :visible.sync="detailShow" center width="1200px"
               @close="detailDialog">
      <div>
        <el-divider :style="{ 'font-size': '16px', 'margin-top': '20px', 'margin-bottom': '20px' }"
                    content-position="left" >基础配置</el-divider>
        <el-form :model="form" :label-width="formLabelWidth" size="mini" class="detail">
          <el-form-item label="需求名称：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            {{ form.demandName }}
          </el-form-item>
          <el-form-item label="优先级：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            {{ getPriorityText(form.priority) }}
          </el-form-item>
          <el-form-item label="主控信息：" :label-width="formLabelWidth" style="display: inline-block; width: 40%;">
            <span>{{ form.devIcMseries }},{{ form.devIcMcode }}</span>
          </el-form-item>
          <el-form-item label="屏幕形状：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            <span>{{ getShapeText(form.devScrShape) }}</span>
          </el-form-item>
          <el-form-item label="分辨率：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            <span>{{ form.devScrDpi }}</span>
          </el-form-item>
          <el-form-item label="是否带缩略图：" :label-width="formLabelWidth" style="display: inline-block; width: 40%;">
            <span>{{ form.thumbnailStatus === '0' ? '否' : '是' }}</span>
          </el-form-item>
          <el-form-item label="项目类型：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            <span>{{ getTypeText(form.type) }}</span>
          </el-form-item>
          <el-form-item label="项目经理：" :label-width="formLabelWidth" style="display: inline-block; width: 30%;">
            <span>{{ form.projectManager }}</span>
          </el-form-item>
          <el-form-item label="主程开发：" :label-width="formLabelWidth" style="display: inline-block; width: 40%;">
            <span>{{ form.masterDeveloper }}</span>
          </el-form-item>
          <el-form-item label="备注：" :label-width="formLabelWidth" style="display: inline-block; width: 100%;">
            <span>{{ form.remark }}</span>
          </el-form-item>
        </el-form>
      </div>
      <el-divider :style="{ 'font-size': '16px', 'margin-top': '20px', 'margin-bottom': '20px' }"
                  content-position="left" v-if="form.kind !== '2'">设计资源配置</el-divider>
        <el-table :data="form.crmDemandViewList" border style="width: 100%" v-if="form.kind !== '2'">
        <el-table-column type="index" fixed :index="sort" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="dialNameZh" label="表盘名称" align="center"></el-table-column>
        <el-table-column label="预览图" width="144" align="center">
          <template v-slot="scope">
            <img style="width: 120px;" :src="scope.row.newPreviewUrl" alt="预览图">
          </template>
        </el-table-column>
        <el-table-column label="表盘大小（含缩略图）" align="center" >
          <template v-slot="scope">
            {{scope.row.dialSize}}kb
          </template>
        </el-table-column>
        <el-table-column label="表盘大小（不含缩略图）" align="center" >
          <template v-slot="scope">
            {{ scope.row.resSize }}kb
          </template>
        </el-table-column>
        <el-table-column label="表盘类型" align="center" >
          <template v-slot="scope">
            <span>{{ getDialTypeText(scope.row.dialTypeId) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 20px; text-align: left;" v-if="form.kind !== '2'">
        所占空间：
        含缩略图-{{ form.dialSizeTotal }} KB，
        不含缩略图-{{ form.resSizeTotal }} KB
      </div>
      <div style="margin-top: 20px; text-align: left;">
        <!-- 文件名显示并添加下载链接 -->
        附件：
        <a v-if="form.annexUrl" :href="form.annexUrl" download :title="form.annexName">
          {{ form.annexName }}
        </a>
      </div>
      <div style="margin-top: 20px; text-align: left;">
        <el-link type="primary" @click="handleDemandLogClick(form)" >查看操作记录</el-link>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialog" :disabled="submitLoading">取 消</el-button>
      </div>
    </el-dialog>

    <Toast :dialogVisible="dialogVisible" @isDelete="deleteDataApi"></Toast>
    <DemandLog :id="`${routerDialId}`" @isDev="demandLogDialogShow = false"
               :demandLogDialogShow="demandLogDialogShow"></DemandLog>

  </div>
</template>

<script>
import { post } from '@/api/my_axios'
import { changSort } from '@/utils/aqi'
import UpLoads from '@@/upLoads/UpLoads.vue'

export default {
  name: '',
  components: { UpLoads },
  data () {
    return {
      annexDialogShow: false, // 附件弹窗
      demandLogDialogShow: false, // 日志弹窗
      detailShow: false, // 详情
      showImportData: false,
      submitLoading: false, // 按钮loading
      dialogFormVisible: false,
      dialogVisible: false,
      dialogShowS: false,
      judgeUserShow: false,
      userInfo: {},
      form: {
        demandId: '',
        demandName: '',
        kind: '',
        type: '',
        priority: '',
        status: '',
        thumbnailStatus: '',
        devIcMseries: '',
        devIcMcode: '',
        devScrShape: '',
        devScrDpi: '',
        devIcFlash: '',
        projectManager: '',
        masterDeveloper: '',
        startUpTime: '',
        finishTime: '',
        remark: '',
        devId: '',
        reserveCount: '',
        reserveSpace: '',
        thumbnailSizeTotal: 0,
        resSizeTotal: 0,
        dialSizeTotal: 0,
        dailIdCount: 0,
        crmDemandViewList: [],
        annexName: '',
        annexUrl: '',
        annexSize: ''
      },
      importData: {
        loading: false,
        submitLoading: false,
        list: [],
        multipleSelection: [], // 多选
        selectedCount: 0, // 当前选中的数据
        totalDialSize: 0, // 含缩略图总大小
        totalResSize: 0, // 不含缩略图总大小
        pageNum: 1,
        pageSize: 10,
        total: 0,
        queryValue: '',
        dialId: '',
        masterControlPlatform: '',
        mainControlModel: '',
        shape: '',
        dpiWh: '',
        dialType: '',
        dialSize: '',
        resSize: ''
      },
      list: [],
      userData: [], // 用户
      configurationList: [],
      statisticsData: [],
      devIcMseriesData: [],
      devScrDpiData: [],
      devIcMcodeData: [],
      devScrShapeData: [], // 屏幕形状
      devIcFlashData: [], // flash存储空间
      deviceKindData: [], // 项目品类
      priorityData: [], // 优先级
      configurationData: [], // 基础配置数据
      fileList: [], // 附件
      uploadUrl: '/api', // 自定义上传接口
      userName: this.$route.query.userName,
      createBy: '',
      formLabelWidth: '140px',
      pageSize: 20,
      pageNum: 1,
      total: 0,
      id: '',
      queryValue: '',
      devIcMseries: '',
      devIcMcode: '',
      devScrShape: '',
      devScrDpi: '',
      queryId: '',
      kind: '',
      status: '',
      routerDialId: '',
      rules: {
        projectManager: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        demandName: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        kind: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        priority: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        type: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        devIcMseries: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        devIcMcode: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        devScrDpi: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        devScrShape: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        thumbnailStatus: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        devIcFlash: [{ required: true, message: '必填项不能为空！', trigger: 'change' }]
      },
      statusData: [
        { value: '0', label: '待启动' },
        { value: '1', label: '进行中' },
        { value: '2', label: '已延期' },
        { value: '3', label: '已完成' },
        { value: '4', label: '已取消' }
      ],
      typeData: [
        { value: 'domestic', label: '国内版（公版）' },
        { value: 'overseas', label: '海外版' }
      ],
      thumbnailStatusData: [
        { value: '1', label: '是' },
        { value: '0', label: '否' }
      ],
      dialTypeData: [
        { value: '112', label: '数字' },
        { value: '113', label: '模拟' }
      ],
      dialSizeData: [
        { value: 40, label: '≤40 kb' },
        { value: 50, label: '≤50 kb' },
        { value: 100, label: '≤100 kb' },
        { value: 140, label: '≤140 kb' },
        { value: 200, label: '≤200 kb' },
        { value: 250, label: '≤250 kb' },
        { value: 500, label: '≤500 kb' },
        { value: 1024, label: '≤1M' }
      ]
    }
  },

  watch: {
    'form.devIcMseries' (val) {
      if (val) {
        this.getSysDictList(val)
      }
    },
    showImportData (newVal) {
      if (newVal) {
        this.handleImportDataOpen()
      }
    }
  },

  mounted () {
    this.getRoleCascadeRelation()
    this.$store.dispatch('getUserData').then(res => {
      this.userInfo = res.data.user
      this.judgeUserShow = this.userInfo.userType !== '02'
      this.getDictSortData()
      this.getDemandStatistics()
      this.getDemandList()
    })
  },

  computed: {
    // 根据 kindList 动态过滤下拉框选项
    filteredKindData () {
      const value = this.$store.state.module1.UserInfo.kind || ''
      const allowedKinds = value.split(',') // 将 kindList 转换为数组
      return this.deviceKindData.filter((item) => allowedKinds.includes(item.value)) // 根据 kindList 过滤选项
    }
  },

  methods: {
    // 排序 （序号）
    sort (index) {
      return changSort(index, this.pageNum, this.pageSize)
    },

    // 时间选择要大于当前的系统时间
    startPickerOptions (value) {
      return {
        disabledDate (time) {
          if (value) {
            // 禁用如果结束时间不为空，则小于结束时间,大于当前时间
            return (time.getTime() < Date.now() - 8.64e7 || new Date(value).getTime() - 8.64e7 < time.getTime())
          } else {
            // 开始时间不选时，结束时间最大值小于等于当天
            return time.getTime() < Date.now() - 8.64e7
          }
        }
      }
    },

    // 结束时间不能小于开始时间
    endPickerOptions (value) {
      return {
        disabledDate (time) {
          if (value) {
            // 禁用如果开始时间不为空，则结束时间大于开始时间一天
            return new Date(value).getTime() > time.getTime() - 8.64e7
          } else {
            // 开始时间不选时，结束时间最大值小于等于当天
            return time.getTime() < Date.now() - 8.64e7
          }
        }
      }
    },

    // 主控平台转化
    getMasterControlPlatformText (value) {
      if (value) {
        const devFuncArr = value.split(',')
        const newDevFunc = []
        devFuncArr.forEach(item => {
          this.devIcMseriesData.forEach(ele => {
            if (ele.value === item) newDevFunc.push(ele.label)
          })
        })
        return newDevFunc.join(',')
      }
      return ''
    },

    // 项目类型转化
    getTypeText (value) {
      const dto = this.typeData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    // 优先级转化
    getPriorityText (value) {
      const dto = this.priorityData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    // 表盘类型转化
    getDialTypeText (value) {
      const dto = this.dialTypeData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    // 状态转化
    getStatusText (value) {
      const dto = this.statusData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    // 项目品类的转化
    getDeviceKindText (value) {
      // 使用find方法查找特定元素对应的对象
      const selectedItem = this.deviceKindData.find(item => item.value === value)
      // 元素不存在时的处理
      return selectedItem ? selectedItem.label : ''
    },

    // 屏幕转化
    getShapeText (value) {
      const dto = this.devScrShapeData.find(v => v.value === value)
      return dto ? dto.label : ''
    },

    // 打开日志弹窗
    handleDemandLogClick (row) {
      this.routerDialId = row.demandId
      this.demandLogDialogShow = true
    },

    // 查看详情
    handleDetail (data) {
      this.detailShow = true
      Object.keys(data).forEach(key => {
        this.form[key] = data[key]
      })
    },

    // 新增
    saveDataForm () {
      this.dialogFormVisible = true
      this.form = {
        demandId: '',
        demandName: '',
        kind: '',
        type: '',
        priority: '',
        status: '0',
        thumbnailStatus: '',
        devIcMseries: '',
        devIcMcode: '',
        devScrShape: '',
        devScrDpi: '',
        devIcFlash: '',
        projectManager: '',
        masterDeveloper: '',
        startUpTime: '',
        finishTime: '',
        remark: '',
        devId: '',
        reserveCount: '',
        reserveSpace: '',
        thumbnailSizeTotal: 0,
        resSizeTotal: 0,
        dialSizeTotal: 0,
        dailIdCount: 0,
        crmDemandViewList: [],
        annexName: '',
        annexUrl: '',
        annexSize: ''
      }
    },

    // 附件修改
    handleAnnexClick (data) {
      this.annexDialogShow = true
      Object.keys(data).forEach(key => {
        this.form[key] = data[key]
      })
    },

    // 修改
    handleClick (data) {
      this.dialogFormVisible = true
      Object.keys(data).forEach(key => {
        this.form[key] = data[key]
      })
      this.getBuiltInManagement()
      this.importData.multipleSelection = this.form.crmDemandViewList
      this.showImportData = true
    },

    // 关闭dialog框
    closeDialog () {
      this.detailShow = false
      this.showImportData = false
      this.dialogFormVisible = false
      this.submitLoading = false
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      this.$refs.dialogForm.resetFields()
    },

    // 关闭详情
    detailDialog () {
      this.detailShow = false
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
    },

    // 需求关闭弹窗
    cancelImportDataDialog () {
      this.detailShow = false
      this.showImportData = false
      this.dialogFormVisible = false
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      Object.keys(this.importData).forEach(key => {
        this.form[key] = ''
      })
      this.importData.list = []
      this.importData.multipleSelection = []
    },

    // 关闭详情
    closeAnnexDialog () {
      this.submitLoading = false
      this.annexDialogShow = false
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
    },

    // 下一步弹窗
    nextDialog () {
      this.$refs.dialogForm.validate(valid => {
        if (!valid) return false
        // 查询 devId 数据是否存在
        this.$store.dispatch('getMaterielBasicConfiguration', {
          pageSize: 1,
          pageNum: 1,
          queryValue: this.form.demandName,
          kind: this.form.kind,
          type: this.form.type,
          devIcMseries: this.form.devIcMseries,
          devIcMcode: this.form.devIcMcode,
          devScrDpi: this.form.devScrDpi,
          devScrShape: this.form.devScrShape,
          devIcFlash: this.form.devIcFlash
        }).then(req => {
          this.configurationData = []
          if (req && req.code === 200) {
            // 校验是否有数据
            if (req.data && Object.keys(req.data).length > 0) {
              this.configurationData = req.data
              // 如果数据存在，继续保存操作
              this.getBuiltInManagement()
            } else {
              // 数据为空，提示项目未创建
              this.$message({ message: '该需求未配置，请先联系项目经理', type: 'error' })
            }
          } else {
            // 接口返回非 200，提示错误信息
            this.$message({ message: '该需求未配置，请先联系项目经理', type: 'error' })
          }
        }).catch(err => {
          this.$message({ message: '该需求未配置，请先联系项目经理或管理员', type: 'error' })
          console.error('查询错误:', err)
        })
      })
    },

    /**
     * 自定义上传逻辑
     * @param {Object} file 包含文件信息的对象
     */
    customUpload ({ file }) {
      this.form.annexSize = file.size
      // this.form.annexName = file.name // 文件名
      this.submitLoading = true // 设置上传状态
      // 文件目录和文件名
      const directory = 'crm/demand/annex/' + this.$store.state.module1.UserInfo.userId + '/'
      // 设置上传表单参数
      this.uploadForm = {
        fileSrc: file.src,
        directory,
        fileName: file.name
      }

      // 调用上传接口
      post('/api/cms/file/oss/upload/commonFileNew', this.uploadForm)
        .then((res) => {
          if (res && res.code === 200) {
            this.form.annexUrl = res.data.url // 保存上传后的文件 URL
            this.form.annexName = res.data.name // 保存上传后的文件名
          } else {
            this.$message.error('附件上传失败，请稍后重试！')
          }
        }).finally(() => {
          this.submitLoading = false // 重置上传状态
        })
    },

    getDemandList () {
      this.list = []
      if (!this.judgeUserShow) {
        this.createBy = this.userInfo.userName
      }
      if (this.userName && this.userInfo.userType !== '00') {
        this.createBy = this.userName
      }
      this.$store.dispatch('getDemandList', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        queryValue: this.queryValue,
        status: this.status,
        kind: this.kind,
        createBy: this.createBy
      }).then(res => {
        this.list = res.data
        this.total = res.total
      })
    },

    async getDemandStatistics () {
      // 字段名称与展示文本的映射关系
      const labelMapping = {
        total: '需求总数',
        count0: '待启动',
        count1: '进行中',
        count2: '已延期',
        count3: '已完成',
        count4: '待启动' // 如果有重复逻辑，请确认业务需求
      }

      try {
        // 如果是外部客户，设置 createBy 的值
        if (!this.judgeUserShow) {
          this.createBy = this.userInfo.userName
        }

        // 如果 this.userName 存在，则使用该值
        if (this.userName) {
          this.createBy = this.userName
        }

        // 调用接口获取数据
        const res = await this.$store.dispatch('getDemandStatistics', {
          createBy: this.createBy
        })

        const data = res.data || {}

        // 处理数据并映射到对应的展示文本，如果没有数据则设置为默认 0
        this.statisticsData = Object.keys(labelMapping).map((key) => ({
          label: labelMapping[key] || key, // 显示对应的文本
          value: data[key] || 0 // 如果数据没有值，则使用默认值 0
        }))
      } catch (error) {
        // 错误处理，如果接口请求失败，设置默认值
        this.statisticsData = [
          { label: '需求总数', value: 0 },
          { label: '待启动', value: 0 },
          { label: '进行中', value: 0 },
          { label: '已延期', value: 0 },
          { label: '已完成', value: 0 },
          { label: '待启动', value: 0 } // 如果有重复项，也可以在此修改
        ]
        console.error('获取数据失败:', error)
      }
    },

    saveDataApi () {
      this.$refs.dialogForm.validate(valid => {
        if (!valid) return false
        if (this.importData.selectedCount <= 0) {
          this.$message.error('请先选择数据！')
          return
        }
        // 从配置从取值比较
        const reserveSpace = this.configurationData && this.configurationData.length > 0
          ? this.configurationData[0].reserveSpace
          : 140
        const reserveCount = this.configurationData && this.configurationData.length > 0
          ? this.configurationData[0].reserveCount
          : 6
        // 检查表盘数量
        const resultSize = this.form.thumbnailStatus === '0' ? this.importData.totalResSize : this.importData.totalDialSize
        if (this.importData.selectedCount > reserveCount) {
          this.$confirm(`<b>当前选择表盘已超${reserveCount}个，是否确认提交？</b>
            <br>如确认提交，请联系我司项目经理对功能进行调整； `, '确认提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true // 允许使用 HTML 标签
          }).then(confirmResult => {
            if (!confirmResult) return // 用户点击取消，退出后续操作

            // 检查表盘总大小（假设totalDialSize是以KB为单位）
            if (resultSize >= reserveSpace) { // 如果总大小超过100KB
              this.$confirm(`<b>当前选择表盘已超${reserveSpace}kb，是否确认提交？</b>
                <br>如确认提交，请联系我司项目经理对功能进行调整；`, '确认提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true // 允许使用 HTML 标签
              }).then(sizeConfirmResult => {
                if (!sizeConfirmResult) return // 用户点击取消，退出后续操作

                // 如果到这里还没有返回，说明所有条件（或用户确认的超出条件）都已满足
                this.prepareFormDataAndSubmit()
              })
            } else {
              // 表盘总大小在有效范围内，直接提交
              this.prepareFormDataAndSubmit()
            }
          })
        } else {
          if (resultSize >= reserveSpace) {
            this.$confirm(`<b>当前选择表盘已超${reserveSpace}kb，是否确认提交？</b>
                <br>如确认提交，请联系我司项目经理对功能进行调整；`, '确认提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              dangerouslyUseHTMLString: true // 允许使用 HTML 标签
            }).then(sizeConfirmResult => {
              if (sizeConfirmResult) {
                this.prepareFormDataAndSubmit()
              }
            })
          } else {
            // 表盘数量和总大小都在有效范围内，直接提交
            this.prepareFormDataAndSubmit()
          }
        }
      })
    },

    prepareFormDataAndSubmit () {
      // 准备表单数据
      if (Array.isArray(this.importData.multipleSelection) && this.importData.multipleSelection.length > 0) {
        this.form.dialIdList = this.importData.multipleSelection.map(x => x.dialId)
      }

      // 设置提交加载状态
      this.submitLoading = true
      this.form.status = '0'
      // 提交表单数据
      post('/api/crm/sys/manage/demand/saveInfo', this.form).then(req => {
        if (req && req.code === 200) {
          this.$message({ message: '保存成功', type: 'success' })
        } else {
          this.$message({ message: '保存失败', type: 'error' })
        }
      }).finally(() => {
        this.closeDialog()
        this.getDemandList()
        this.getDemandStatistics()
      })
    },

    saveAnnexDataApi () {
      this.submitLoading = true
      post('/api/crm/sys/manage/demand/saveInfo', this.form).then(req => {
        if (req && req.code === 200) {
          this.$message({ message: '保存成功', type: 'success' })
        } else {
          this.$message({ message: '保存失败', type: 'error' })
        }
      }).finally(() => {
        this.closeAnnexDialog()
        this.getDemandList()
      })
    },

    deleteDataApi (type) {
      if (type === 'ok') {
        post('/api/crm/sys/manage/material/configuration/deleteById', this.id
        ).then(req => {
          if (req && req.code === 200) {
            this.$message({ message: req.msg, type: 'success' })
            this.getDemandStatistics()
            this.getDemandList()
          }
        })
      }
      this.dialogVisible = false
    },

    changeStatus4 (row) {
      // const params = {
      //   demandId: '',
      //   status: '4'
      // }
      // params.demandId = row.demandId
      row.status = '4'
      this.$confirm('是否确定取消该需求?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        post('/api/crm/sys/manage/demand/saveInfo', row).then(res => {
          if (res.code === 200) {
            this.$message({ message: '成功', type: 'success' })
            this.getDemandStatistics()
            this.getDemandList()
          }
        })
      })
    },

    getMaterielBasicConfiguration () {
      this.$store.dispatch('getMaterielBasicConfiguration', {
        pageSize: 1000,
        pageNum: 1,
        kind: this.form.kind,
        type: this.form.type,
        devIcMseries: this.form.devIcMseries,
        devIcMcode: this.form.devIcMcode,
        devScrDpi: this.form.devScrDpi,
        devIcFlash: this.form.devIcFlash
      }).then(res => {
        this.configurationList = res.data
        this.total = res.total
      })
    },

    async getBuiltInManagement () {
      this.showImportData = true
      this.importData.list = []
      this.$store.dispatch('getBuiltInManagement', {
        pageSize: 1000,
        pageNum: 1,
        status: '2',
        kind: this.form.kind,
        type: this.form.type,
        masterControlPlatform: this.form.devIcMseries,
        mainControlModel: this.form.devIcMcode,
        dpiWh: this.form.devScrDpi,
        shape: this.form.devScrShape,
        thumbnailStatus: this.form.thumbnailStatus === '0' ? '' : '1',
        queryValue: this.importData.queryValue,
        dialTypeId: this.importData.dialType,
        dialSize: this.importData.dialSize,
        resSize: this.importData.resSize
      }).then(res => {
        if (res.code === 200) {
          this.importData.list = res.data
          this.importData.total = res.total
          // 数据加载完成后调用打开逻辑
          this.handleImportDataOpen()
        } else {
          // 如果响应不是 200，可以选择弹出提示或处理异常
          this.$message.error(`加载数据失败: ${res.message || '未知错误'}`)
        }
      })
      if (!this.importData.list || this.importData.list.length === 0) {
        this.importData.list = this.form.crmDemandViewList
      }
    },

    // 根据主控平台获取对应主控型号
    getSysDictList (value) {
      this.$store.dispatch('getSysDictItemList', value).then(res => {
        this.devIcMcodeData = res
      })
    },

    // 数据字典配置分类项获取
    getDictSortData (type) {
      // 需求优先级
      this.$store.dispatch('getSysDictItemList', 'requirements_prioritization').then(res => {
        this.priorityData = res
      })

      // 项目品类
      this.$store.dispatch('getSysDictItemList', 'deviceKind').then(res => {
        this.deviceKindData = res
      })

      // 分辨率
      this.$store.dispatch('getSysDictItemList', 'devScrDpi').then(res => {
        const shieldDp = ['320x380', '410x502', '410x492', '172x320']
        const newArr = []
        res.forEach(item => {
          if (!shieldDp.includes(item.value)) newArr.push(item)
        })
        this.devScrDpiData = newArr
      })

      // 主控平台系列
      this.$store.dispatch('getSysDictItemList', 'devIcMseries').then(res => {
        this.devIcMseriesData = res
      })

      // 屏幕形状
      this.$store.dispatch('getSysDictItemList', 'devScrShape').then(res => {
        this.devScrShapeData = res
      })

      // flash存储空间
      this.$store.dispatch('getSysDictItemList', 'devIcFlash').then(res => {
        this.devIcFlashData = res
      })
    },

    // 用户级联关系
    getRoleCascadeRelation () {
      this.$store.dispatch('getRoleCascadeRelation').then(res => {
        const item = res.find(item => item.firstLevelId === '4')
        if (item && item.userInfoVOList && item.userInfoVOList.length) {
          this.userData = item.userInfoVOList.map(user => ({
            value: user.userName, // 提交时取 userName
            label: user.nickName // 显示昵称
          }))
        } else {
          this.userData = []
        }
      })
    },

    rowKey (row) {
      return row.dialId
    },

    // 弹窗打开时自动勾选已有数据
    async handleImportDataOpen () {
      // 判断 crmDemandViewList 是否存在且有数据
      if (Array.isArray(this.form.crmDemandViewList) && this.form.crmDemandViewList.length > 0) {
        const preselectedIds = this.form.crmDemandViewList.map((item) => item.dialId) // 提取已选的 dialId 列表
        this.importData.loading = true
        // 等待下一次 DOM 更新后操作
        this.$nextTick(() => {
          const rowsToSelect = this.importData.list.filter((row) =>
            preselectedIds.includes(row.dialId)
          )
          this.selectRowsInTable(rowsToSelect)
        })

        this.importData.loading = false
      }
    },

    // 选中表格行
    selectRowsInTable (rows) {
      this.$refs.importTable.clearSelection() // 清除所有选中状态
      rows.forEach((row) => {
        this.$refs.importTable.toggleRowSelection(row, true) // 逐行勾选
      })
      this.selectImportIds(rows) // 更新统计数据
    },

    selectImportIds (val) {
      this.importData.multipleSelection = val
      this.importData.selectedCount = val.length
      this.importData.totalDialSize = val.reduce((sum, row) => sum + Number(row.dialSize), 0)
      this.importData.totalResSize = val.reduce((sum, row) => sum + Number(row.resSize), 0)
    },

    handleImportDataQuery () {
      this.importData.pageNum = 1
      this.getBuiltInManagement()
      // this.importData.multipleSelection = this.form.crmDemandViewList
      if (Array.isArray(this.form.crmDemandViewList) && this.form.crmDemandViewList.length > 0) {
        this.$nextTick(() => {
          const preselectedIds = this.importData.crmDemandViewList.map((row) => row.dialId)
          const rowsToSelect = this.importData.list.filter((row) =>
            preselectedIds.includes(row.dialId)
          )
          this.selectRowsInTable(rowsToSelect) // 恢复勾选状态
        })
      }
    },

    importSizeChange (size) {
      this.importData.pageSize = size
      this.getBuiltInManagement()
    },

    importCurrentChange (num) {
      this.importData.pageNum = num
      this.getBuiltInManagement()
    },

    handleQuery () {
      this.pageNum = 1
      this.getDemandList()
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.getDemandList()
    },

    handleCurrentChange (val) {
      this.pageNum = val
      this.getDemandList()
    },

    handleButtonClick (data) {
      this.id = data.id
      this.dialogVisible = true
    },

    // 返回上一页
    retPath () {
      this.$router.replace({ path: '/CustomerManagement' })
    },

    is_show_button (name) {
      let show = false
      this.$store.state.module1.menu_list.forEach(v => {
        if (v.path === name) {
          show = true
        }
      })
      return show
    }
  }
}
</script>

<style lang='scss'>
.page_format {
  padding: 56px 20px 140px 20px;
}

.search-form {
  margin-top: 10px;
}

.icon-image {
  width: auto;
  height: auto;
  object-fit: cover;
}
</style>
